<template>
    <div>
        <Card dis-hover bordered="true">
            <h3>
                {{taskName}}
            </h3>
            <ButtonGroup slot="extra">
                <Button @click="returnTo">
                    返回
                    <Icon type="ios-arrow-forward" />
                </Button>
            </ButtonGroup>
        </Card>
        <Divider />
        <Row>
            <i-col span="24">
                <Spin fix v-if="spinShow">
                    <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
                    <div>Loading</div>
                </Spin>
                <div :style="{height: bodyHeight + 'px', overflowY: 'auto'}">
                <Tabs>
                    <TabPane label="基本信息">
                        <div :style="">
                            <Form label-position="top">
                                <Row>
                                    <i-col span="24">
                                        <FormItem label="排查对象：" prop="reportDesc">
                                            <Input v-model="apsgData.parentOrgName + '>>' +apsgData.projectname" readonly/>
                                        </FormItem>
                                    </i-col>
                                </Row>
                                <Row>
                                    <i-col span="24">
                                        <FormItem label="排查人所属机构：" prop="reportDesc">
                                            <Input v-model="apsgData.parentOrgName2 != null ? apsgData.parentOrgName2 + '>>' + apsgData.orgName: apsgData.orgName" readonly/>
                                        </FormItem>
                                    </i-col>
                                </Row>
                                <Row :gutter="16">
                                    <i-col span="8">
                                        <FormItem label="隐患等级" prop="level">
                                            <Input v-model="apsgData.level" readonly/>
                                        </FormItem>
                                    </i-col>
                                    <i-col span="8">
                                        <FormItem label="整改时限（天）：" prop="reportDesc">
                                            <Input v-model="apsgData.recPeriod" readonly/>
                                        </FormItem>
                                    </i-col>
                                </Row>
                                <Row>
                                    <i-col span="24">
                                        <FormItem label="隐患内容" prop="content">
                                            <Input v-model="apsgData.content" type="textarea" readonly/>
                                        </FormItem>
                                    </i-col>
                                </Row>
                                <Row>
                                    <i-col span="24">
                                        <FormItem label="整改记录" prop="rectifyrecord">
                                            <Input v-model="apsgData.rectifyrecord" type="textarea" readonly/>
                                        </FormItem>
                                    </i-col>
                                </Row>
                                <Row :gutter="16">
                                    <i-col span="8">
                                        <FormItem label="隐患整改人" prop="level">
                                            <Input v-model="apsgData.rectifyrp" readonly/>
                                        </FormItem>
                                    </i-col>
                                    <i-col span="8">
                                        <FormItem label="隐患整改时间" prop="reportDesc">
                                            <Input v-model="apsgData.governTimeStr" readonly/>
                                        </FormItem>
                                    </i-col>
                                </Row>
                            </Form>
                        </div>
                    </TabPane>
                    <TabPane label="图片附件">
                        <Row>
                            <i-col span="24">
                                <Divider orientation="left">隐患图片</Divider>
                                <div v-if="reportFile.length != 0">
                                    <div v-for="(item, index) in reportFile" :key="index" style="float: left; width: 100px; margin-left: 10px">
                                        <router-link target="_blank" :to="{path:'/imgDetails',query:{id:item.id}}">
                                            <img  :src="item.picture"  style="width: 100px; height: 100px; margin: 10px"/>
                                        </router-link>
                                    </div>
                                </div>
                                <p v-else>暂无图片</p>
                            </i-col>
                        </Row>
                        <Row>
                            <i-col span="24">
                                <Divider orientation="left">整改图片</Divider>
                                <div v-if="modifyFile.length != 0">
                                    <div v-for="(item, index) in modifyFile" :key="index" style="float: left;width: 100px; margin-left: 10px">
                                        <router-link target="_blank" :to="{path:'/imgDetails',query:{id:item.id}}">
                                            <img  :src="item.picture" style="width: 100px; height: 100px; margin: 10px"/>
                                        </router-link>
                                    </div>
                                </div>
                                <p v-else>暂无图片</p>
                            </i-col>
                        </Row>
                    </TabPane>
                </Tabs>
                </div>
            </i-col>
        </Row>
        <Modal title="附件查看" v-model="visible">
            <img :src="fileImgSrc" style="width: 100%">
            <div slot="footer" >
                <Button @click="visible=false" class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
    var cascaderDom = () => import('@/components/cascader-dom.vue');
    import {sessionStorage} from '@/common/cacheUtils.js';
    import {Api} from '../../../api'
    // import workflowForm from "@/components/workflowForm.vue"
    export default {
        name: "hidHazardForm",
        components:{
            cascaderDom,
            // workflowForm
        },
        data(){
            const validateFile = (rule, value, callback) => {
                if(this.isModifyFile){
                    if(this.fileList.length == 0&& this.modifyFile.length == 0) {
                        this.$Message.error({ content: '请上传整改图片', duration: 4});
                        return callback(new Error('请上传附件'));
                    } else {
                        callback();
                    }
                }else if(this.isReportFile){
                    if(this.fileList.length == 0 && this.reportFile.length == 0) {
                        this.$Message.error({ content: '请上传隐患图片', duration: 4});
                        return callback(new Error('请上传附件'));
                    } else {
                        callback();
                    }
                }
            };
            return{
                taskName: '',
                taskInfo:{},
                user:{},
                visible: false,
                fileImgSrc: '',
                createDateStr: '',
                spinShow: true,
                isManageRole: false,
                buttonloading: false,
                single: true,
                isLevel: false,
                ifDynamicAudits: false,
                isModifyFile: false,
                isDepartment: false,
                departmentName: '',
                isDepartmentUser: false,
                isRectifyrp: false,
                isRectifyrecord: false,
                isIntervention: false,
                isRole: false,
                ifRoute: false,
                isDivisionRoute: false,
                isReportFile: false,
                roleName: '',
                formData: {
                },
                ruleCustom: {
                    level: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    revisemaindept: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    dynamicAudits: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    rectifyrp: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    rectifyrecord: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    intervention: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    recPeriod: [
                        {
                            type: 'integer',
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    modifyFile: [
                        {
                            required: true,
                            validator: validateFile,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    route: [
                        {
                            type: 'integer',
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                    remark: [
                        {
                            required: true,
                            message: '  ',
                            trigger: 'blur,change'
                        }
                    ],
                },
                bodyHeight: '',
                footerHeight: 100,
                routeList: [
                    {
                        id: 1,
                        name: '合格'
                    },
                    {
                        id: 2,
                        name: '不合格'
                    }
                ],
                user:{},
                taskInfo: {},
                fileUrl: '',
                apsgData: {},
                formList: [],
                reportFile: [],
                modifyFile: [],
                fileList: [],
                orgList: [],
                userList: [],
                userList2: [],
                interventionList: [
                    {
                        id: "1",
                        name: '是'
                    },
                    {
                        id: "2",
                        name: '否'
                    }
                ],
                roleUserList: [],
                levelList: [
                   {
                        id: 'Ⅰ',
                        label: 'Ⅰ'
                    },
                    {
                        id: 'Ⅱ',
                        label: 'Ⅱ'
                    },
                    {
                        id: 'Ⅲ',
                        label: 'Ⅲ'
                    },
                    {
                        id: 'Ⅳ',
                        label: 'Ⅳ'
                    }
                ],
                roleId: '',
                variables: {}
            }
        },
        mounted() {
            this.bodyHeight = window.innerHeight - 225;
            this.taskName = this.$route.query.taskName;
            this.query();
        },
        methods: {
            returnTo(){
                   this.$router.go(-1);
            },
            query(){
                this.formData = {
                    userName: this.user.userName,
                    taskId: this.taskInfo.taskId,
                    createUserId: this.user.userId,
                    procinstId: this.taskInfo.procinstId,
                }
                this.$http.get(Api.apsgInverstigation + '/'+ this.$route.query.workId, {
                    params: {}
                }).then(function(response){
                    this.apsgData = response.data;
                    this.$set(this.formData, 'revisemaindept', response.data.revisemaindept);
                    this.createDateStr = this.formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss');
                        this.spinShow = false;
                }, function(res){
                    this.$Message.error('请求失败');
                });
                this.queryOrg();
                this.$http.get(Api.uploadPTWFiles  + '/' + this.$route.query.workId + '/files/picture',{
                    params: {},
                }).then((res) => {
                    res.data.data.map((i) =>{
                        if(i.field == 'report'){
                            this.reportFile.push(i);
                        }
                        if(i.field == "modify"){
                            this.modifyFile.push(i);
                        }
                    })
                })
            },
            setOrgName(data){
                this.formData.dynamicAudits = data[data.length - 1];
            },
            approvalInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid){
                        if(this.fileUrl!= ''){ this.fileList.map((i)=>{ this.$refs.upload.post(i); }) }
                        this.saveInfo();
                        if(this.isManageRole&&this.formData.route == 1 ){
                            this.formData.route = 3;
                        }
                        this.buttonloading = true;
                        this.$http.get(Api.taskComplete, {
                            params: this.formData
                        }).then(function(response){
                            if(response.data.status == 200){
                                this.$Message.success({content: '保存成功', duration: 4});
                                this.returnTo();
                            }else{
                                this.$Message.error({ content: '保存失败', duration: 4});
                            }
                            this.buttonloading = false;
                        });
                    }
                });
            },
            saveInfo(){
                let data = {
                    id: this.taskInfo.workId,
                    revisemaindept: this.isDepartment ? this.formData.revisemaindept: null,
                    rectifyrp: this.isRectifyrp ? this.formData.dynamicAudits : null,
                    rectifyrecord: this.isRectifyrecord? this.formData.rectifyrecord: null,
                    level: this.isLevel? this.formData.level: null,
                    recPeriod: this.isLevel? this.formData.recPeriod: null,
                    remark: this.formData.remark? this.formData.remark: null,
                }
                this.$http.put(Api.apsgInverstigation, data);
            },
            queryOrg(){
                this.$http.get(Api.orgInfoTree, {
                    params: {
                        parentId: this.user.companyId
                    }
                }).then(function(res){
                    this.orgList = res.data.data;
                })
            },
            queryUsers(orgId){
                    this.$http.get(Api.positionOrgUsers + orgId, {
                        params: {}
                    }).then(function(res){
                        this.userList = res.data.data;
                    })
                    this.$http.get(Api.orgUsers + orgId, {
                        params: {}
                    }).then(function(res){
                        this.userList2 = res.data.data;
                    })
            },
            changeRectifyrp(id){
                if(id == 1) {
                    this.isRectifyrp = false;
                    this.isRole = true;
                }else{
                    this.isRectifyrp = true;
                    this.isRole = false;
                }
            },
            getRoleUser(roleId){
                let user = this.user;
                this.$http.get(Api.apsgRoleUser, {
                    params: {companyName:  user.companyName, roleId: roleId}
                }).then(function(res){
                    res.data.map((i)=>{
                        this.roleUserList.push({id: i.verifyuserid, label: i.userName });
                    })
                }, function(res){
                    this.$Message.error('请求失败');
                });
            },
            beforeUpload (file) {
                if(file.type.indexOf("image") == -1){
                    this.$Notice.warning({
                        title: '请上传图片格式附件！',
                    });
                }else{
                    let self = this;
                    let keyID = Math.random().toString().substr(2);
                    file['keyID'] = keyID;
                    let reader = new FileReader();
                    reader.readAsDataURL(file);
                    reader.onload = function(ev) { //文件读取成功完成时触发
                        file['imgBase64'] = ev.target.result; //获得文件读取成功后的DataURL,也就是base64编码
                        self.fileList.push(file);
                    }
                }
                return false;
            },
            removeFile(keyID){
                this.fileList = this.fileList.filter(item => {
                    return item.keyID != keyID
                })
            },
            removeFile2(file){
                this.$http.delete(Api.uploadMongoFile + "/" + file.id).then((res) => {
                    this.reportFile.splice(this.reportFile.indexOf(file), 1);
                }).catch(e => {
                    this.$Message.error("附件删除失败");
                });
            },
            viewFile(imgBase64){
                this.visible = true;
                this.fileImgSrc = imgBase64;
            },
            changeDivision(id){
                if(id == 1 && this) {
                    this.isRole = true;
                }else{
                    this.isRole = false;
                }
            },
            changeLevel(id){
                if(id == 'Ⅳ'){
                    this.formData.recPeriod = 2;
                }else if(id == 'Ⅲ'){
                    this.formData.recPeriod = 5;
                }else if(id == 'Ⅱ'){
                    this.$Notice.warning({title: '已选择二级隐患', duration: 6});
                    this.formData.recPeriod = 10;
                }else if(id == 'Ⅰ'){
                    this.$Notice.warning({title: '已选择一级隐患', duration: 6});
                    this.formData.recPeriod = 30;
                }

                if(this.apsgData.revisemaindept!=undefined){
                    if(id == 'Ⅲ'|| id == 'Ⅳ'){
                        this.isIntervention = false;
                    }else{
                        this.isIntervention = true;
                    }
                }
            },
            changeRoute(id){
                if(this.variables.manageRoute == 1 && this.taskName == '主责部门经理安排治理'){
                    if(id==1){
                        this.isDepartment = true;
                        this.isRectifyrp = true;
                        this.isLevel = true;
                    }else{
                        this.isDepartment = false;
                        this.isRectifyrp = false;
                        this.isLevel = false;
                        this.formData.route = 3;
                    }
                }else{
                    if(this.taskName == '安全环保管理人员'){
                        if(id==1){
                            this.isLevel = true;
                            this.isDepartment = true;
                            this.isDepartmentUser = true;
                        }else{
                            this.isLevel = false;
                            this.isDepartment = false;
                            this.isDepartmentUser = false;
                        }

                    }else if(this.taskName == '主责部门经理安排治理'){
                        if(id==1){
                            this.isDepartment = true;
                            this.isRectifyrp = true;
                        }else{
                            this.isDepartment = false;
                            this.isRectifyrp = false;
                        }
                    }
                }
            },
            formatDate(date, fmt) {
                if (typeof date == 'string') {
                    return date;
                }
                if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";
                if (!date || date == null) return null;
                let o = {
                    'M+': date.getMonth() + 1, // 月份
                    'd+': date.getDate(), // 日
                    'h+': date.getHours(), // 小时
                    'm+': date.getMinutes(), // 分
                    's+': date.getSeconds(), // 秒
                    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
                    'S': date.getMilliseconds() // 毫秒
                }
                if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
                for (let k in o) {
                    if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
                }
                return fmt
            },
        }
    }
</script>
<style scoped>
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
</style>
<style scoped>
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>
